<?php

namespace app\admin\model;

use app\common\model\Area;
use app\common\model\Channelapply;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\User as ModelUser;
use app\common\model\user\Alloca;
use Jdy;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text',
        'agent_area',
        'new_nickname',
    ];
    public function getNewNicknameAttr($value, $d)
    {
        return $d['nickname'] . '#' . $d['id'];
    }
    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
            if (isset($changed['channel_level'])) {
                if ($changed['channel_level'] == 0) {
                    $row->is_channel = 0;
                    $row->channeltime = 0;
                    $puser = ModelUser::get(['id' => $row['parent_id']]);
                    if ($puser) {
                        if ($puser['is_channel'] == 0) {
                            $row->channel = $puser['channel'];
                        } else {
                            $row->channel = $puser['id'];
                        }
                    }
                    db('user')->where('channel', $row['id'])->where('is_channel', 1)->update(['channel' => 0]);
                    db('user')->where('channel', $row['id'])->where('is_channel', 0)->update(['channel' => $row->channel]);
                    Channelapply::where('user_id', $row['id'])->delete();
                } else {
                    $row->channeltime = time();
                    $row->is_channel = 1;
                    $uids = [];
                    ModelUser::digui($row->id, $uids);
                    $puser = ModelUser::get(['id' => $row['parent_id']]);
                    if ($puser) {
                        if ($puser['is_channel'] == 0) {
                            $row->channel = 0;
                        } else {
                            $row->channel = $puser['id'];
                        }
                    }
                    db('user')->where('parent_id', $row['id'])->update(['channel' => $row->id]);
                    db('user')->whereIn('id', $uids)->update(['channel' => $row->id]);
                }
            }
            if (isset($changed['parent_id']) && $changed['parent_id']) {
                $puser = db('user')->where('id', $changed['parent_id'])->find();
                if ($puser['is_channel'] == 1) {
                    $row->channel =  $puser['id'];
                } else {
                    $row->channel = $puser['channel'];
                }
            }
            if (isset($changed['parent_id']) && $changed['parent_id']) {
                $puser = db('user')->where('id', $changed['parent_id'])->find();
                if ($puser['is_channel'] == 1) {
                    $row->channel =  $puser['id'];
                } else {
                    $row->channel = $puser['channel'];
                }
            }

            $acct = Admin::where('province', $row['province_id'])->find();
            if (!$acct) {
                exception('该省份未绑定子平台');
            }
            $row->acct_id = $acct->acct_id;
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (float)$changedata['money'] !== (float)$origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
        self::beforeInsert(function ($row) {
            $row->jointime = time();
            if (isset($row['channel_level'])) {
                if ($row['channel_level'] == 0) {
                    $row->is_channel = 0;
                    $row->channeltime = 0;
                    if (isset($row['parent_id']) && $row['parent_id']) {
                        $puser = User::get($row['parent_id']);
                        if ($puser['is_channel'] == 0) {
                            $row->channel = $puser['channel'];
                        } else {
                            $row->channel = $row['parent_id'];
                        }
                    }
                } else {
                    if (isset($row['parent_id']) && $row['parent_id']) {
                        $puser = User::get($row['parent_id']);
                        if ($puser['is_channel'] == 1) {
                            $row->channel = $row['parent_id'];
                        }
                    }
                    $row->channeltime = time();
                    $row->is_channel = 1;
                }
            }
            $acct = Admin::where('province', $row['province_id'])->find();
            if (!$acct) {
                exception('该省份未绑定子平台');
            }
            $row->acct_id = $acct->acct_id;
        });

        self::afterInsert(function ($row) {
            // if (empty($row['jdy_id']) && !empty($row['acct_id']) && ($row['acct_id'] == 50 || $row['acct_id'] == 67)) {
            //     $api = new Jdy(['acct_id' => $row['acct_id']]);
            //     $api->addUser($row);
            // }
        });

        self::afterDelete(function ($row) {
            Admin::where('user_id', $row['id'])->delete();
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function puser()
    {
        return $this->belongsTo('User', 'parent_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function allocas()
    {
        return $this->belongsTo(Alloca::class, 'id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }
    public function lev()
    {
        return $this->belongsTo('app\common\model\user\Level', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getAgentAreaAttr($value, $data)
    {
        if (isset($data['agent_area_ids']) && $data['agent_area_ids']) {
            $arr = explode(',', $data['agent_area_ids']);
            $area = Area::where('id', 'in', $arr)->column('id,name');
            // var_dump($area);
            $str = [];
            foreach ($arr as $v) {
                array_push($str, $area[$v] ?? '');
            }
            return implode(',', $str);
        }
        return '';
    }
}
